package it.softphone.cmc.server.service.impl;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import it.softphone.cmc.server.service.TaskQueueService;
import it.softphone.commons.exception.NullParameterException;

import java.util.List;
import java.util.Map;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;


import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

/**
 * 
 * @author softphone
 *
 */
public class GAETaskQueueServiceImpl implements TaskQueueService {

	@Override
	public void schedule(Method method, String url,	MultivaluedMap<String, String> paramMap, HttpHeaders hh) {
		if( url == null ) throw new NullParameterException("url");
		if( hh == null ) throw new NullParameterException("hh");
		
	    Queue queue = QueueFactory.getDefaultQueue();
	    
	    TaskOptions opts = (method==Method.GET) ? 
	    						withUrl( url ).method(com.google.appengine.api.taskqueue.TaskOptions.Method.GET) :
		    					withUrl( url ).method(com.google.appengine.api.taskqueue.TaskOptions.Method.POST) ;
	    							
	    if( null!=paramMap ) {

	    	for( Map.Entry<String,List<String>> e : paramMap.entrySet()) {
	    		
	    		List<String> values = e.getValue();
	    		
	    		for( String v : values ) opts.param(e.getKey(), v );
	    	}
	    }
	    
	    MultivaluedMap<String, String> headerMap = hh.getRequestHeaders();
	    
	    if( hh!=headerMap ) {

	    	for( Map.Entry<String,List<String>> e : headerMap.entrySet() ) {
	    		
	    		List<String> values = e.getValue();
	    		
	    		for( String v : values ) opts.header(e.getKey(), v );
	    	}
	    }
	    
	    queue.add(opts);
	}



}
